<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function special_activities_add_page($id) {
    return drupal_get_form('special_activities_edit_form',$id);
}

function special_activities_edit_page($id) {
    return drupal_get_form('special_activities_edit_form', $id);
}

function special_activities_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('special_activities', 'special_activities_id', $id);
        if (empty($record)) {
            drupal_set_message(t('专项活动不存在！'), 'status', FALSE);
            return $form;
        }
    }
    // 判断用户角色
    if(!nonghua_user_access('special_activities', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $form['special_activities'] = array(
        '#type' => 'textfield',
        '#title' => '专项活动',
        '#size' => 32,
        '#maxlength' => 50,
//        '#id'=>'special_activities_textfield',
        '#default_value'=>!empty($record)?$record->title:"",
        '#disabled'=>arg(1) == 'edit' && !empty(arg(2)) ? true : false,
//        '#required' => TRUE,
    );
    $form['implementation_region'] = array(
        '#type' => 'textfield',
        '#title' => '实施大区',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->implementation_region:"",
//        '#required' => TRUE,
    );
    $form['implementation_place'] = array(
        '#type' => 'textfield',
        '#title' => '实施地点',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->implementation_place:"",
//        '#required' => TRUE,
    );
    $form['implementation_comment'] = array(
        '#type' => 'textarea',
        '#title' => '实施说明',
        '#size' => 32,
        '#maxlength' => 200,
        '#default_value'=>!empty($record)?$record->implementation_comment:"",
//        '#required' => TRUE,
    );
    $form['farmer_meeting'] = array(
        '#type' => 'textfield',
        '#title' => '农民会议(场次)',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value'=>!empty($record)?$record->farmer_meeting:"",
//        '#required' => TRUE,
    );
    $form['distrbutor_meeting'] = array(
        '#type' => 'textfield',
        '#title' => '经销商会议(场次)',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value'=>!empty($record)?$record->distrbutor_meeting:"",
//        '#required' => TRUE,
    );
    $form['fertilizer_number'] = array(
        '#type' => 'textfield',
        '#title' => '示范肥数量(吨)',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value'=>!empty($record)?$record->fertilizer_number:"",
//        '#required' => TRUE,
    );
    $form['fertilizer_type1'] = array(
        '#type' => 'textfield',
        '#title' => '品种',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->fertilizer_type1:"",
//        '#required' => TRUE,
    );
    $form['fertilizer_type2'] = array(
        '#type' => 'textfield',
        '#title' => '品种',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->fertilizer_type2:"",
//        '#required' => TRUE,
    );
    $form['fertilizer_type3'] = array(
        '#type' => 'textfield',
        '#title' => '品种',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->fertilizer_type3:"",
//        '#required' => TRUE,
    );
    $form['fertilizer_type4'] = array(
        '#type' => 'textfield',
        '#title' => '品种',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->fertilizer_type4:"",
//        '#required' => TRUE,
    );
    $form['fertilizer_type5'] = array(
        '#type' => 'textfield',
        '#title' => '品种',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->fertilizer_type5:"",
//        '#required' => TRUE,
    );
    $form['feature_name'] = array(
        '#type' => 'textfield',
        '#title' => '特色活动名称',
        '#size' => 32,
        '#maxlength' => 50,
        '#default_value'=>!empty($record)?$record->feature_name:"",
//        '#required' => TRUE,
    );
    $form['implementation_number'] = array(
        '#type' => 'hidden',
        '#title' => '实施数量',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value'=>!empty($record)?$record->implementation_number:"",
//        '#required' => TRUE,
    );
    if(arg(1) == 'edit' && !empty(arg(2)) && !empty($record)){
        $form['timestamp'] = array(
            '#type' => 'textfield',
            '#size' => 32,
            '#maxlength' => 50,
            '#id'=>'special_activities_textfield',
            '#default_value'=>!empty($record)?date('Y-m-d H:i:s',$record->timestamp):"",
            '#disabled'=> true,
        );
        $form['#special_activities'] = get_special_activities_allmessages($record);
//        print_r( $form['#special_activities'] );die;
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) != 'add' ? '修改' : '添加',
        '#access' =>nonghua_user_access('special_activities', 'edit', $id, !empty($record) ? $record->author_uid:0, 0) ,
    );
    return $form;
}

function special_activities_edit_form_validate($form, &$form_state) {

    if(empty($form_state['values']['special_activities'])){
        form_set_error('special_activities', '必须填写 专项活动名称');
    }else{
        $special_activities_id =  get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
        if(!empty($special_activities_id) && arg(1) == 'add'){
            form_set_error('special_activities', '专项活动名称已存在');
        }
    }
    if(!empty($form_state['values']['farmer_meeting'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['farmer_meeting']) || (strlen(explode('.',$form_state['values']['farmer_meeting'])[0])>8)) {
            form_set_error('farmer_meeting', "农户会议格式错误");
        }
    }else{
        $form_state['values']['farmer_meeting']=null;
    }
    if(!empty($form_state['values']['distrbutor_meeting'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['distrbutor_meeting']) || (strlen(explode('.',$form_state['values']['distrbutor_meeting'])[0])>8)) {
            form_set_error('distrbutor_meeting', "经销商会议格式错误");
        }
    }else{
        $form_state['values']['distrbutor_meeting'] = null;
    }
    if(!empty($form_state['values']['fertilizer_number'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['fertilizer_number']) || (strlen(explode('.',$form_state['values']['fertilizer_number'])[0])>8)) {
            form_set_error('fertilizer_number', "示范肥数量格式错误");
        }
    }else{
        $form_state['values']['fertilizer_number']=null;
    }
    if(!empty($form_state['values']['implementation_number'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['implementation_number']) || (strlen(explode('.',$form_state['values']['implementation_number'])[0])>8)) {
            form_set_error('implementation_number', "实施数量格式错误");
        }
    }else{
        $form_state['values']['implementation_number'] = null;
    }
}

function special_activities_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address = _get_address_id($form_state);
    if (arg(1) == 'add') { //add new special_activities
        $nid = db_insert('special_activities') // Table name no longer needs {}
                ->fields(array(
                    'title' => $form_state['values']['special_activities'],
                    'implementation_place' => $form_state['values']['implementation_place'],
                    'implementation_region' => $form_state['values']['implementation_region'],
                    'implementation_comment' => $form_state['values']['implementation_comment'],
                    'farmer_meeting' => $form_state['values']['farmer_meeting'],
                    'distrbutor_meeting' => $form_state['values']['distrbutor_meeting'],
                    'fertilizer_number' => $form_state['values']['fertilizer_number'],
                    'fertilizer_type1' => $form_state['values']['fertilizer_type1'],
                    'fertilizer_type2' => $form_state['values']['fertilizer_type2'],
                    'fertilizer_type3' => $form_state['values']['fertilizer_type3'],
                    'fertilizer_type4' => $form_state['values']['fertilizer_type4'],
                    'fertilizer_type5' => $form_state['values']['fertilizer_type5'],
                    'feature_name' => $form_state['values']['feature_name'],
                    'implementation_number' => $form_state['values']['implementation_number'],
                    'author_uid' => $user->uid,
                    'timestamp' => time(),))
                ->execute();
        if ($nid > 0) {
            clear_search_autocomplete_cach();
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            drupal_goto('special_activities/add/'.$nid);
        }
    }else {
    $nid = db_update('special_activities') // edit exsting store. todo: update only modified fields
    ->fields(array(
        'implementation_place' => $form_state['values']['implementation_place'],
        'implementation_region' => $form_state['values']['implementation_region'],
        'implementation_comment' => $form_state['values']['implementation_comment'],
        'farmer_meeting' => $form_state['values']['farmer_meeting'],
        'distrbutor_meeting' => $form_state['values']['distrbutor_meeting'],
        'fertilizer_number' => $form_state['values']['fertilizer_number'],
        'fertilizer_type1' => $form_state['values']['fertilizer_type1'],
        'fertilizer_type2' => $form_state['values']['fertilizer_type2'],
        'fertilizer_type3' => $form_state['values']['fertilizer_type3'],
        'fertilizer_type4' => $form_state['values']['fertilizer_type4'],
        'fertilizer_type5' => $form_state['values']['fertilizer_type5'],
        'feature_name' => $form_state['values']['feature_name'],
        'implementation_number' => $form_state['values']['implementation_number'],
        'author_uid' => $user->uid,))
        -> condition('special_activities_id',$id, '=')
        ->execute();
    if ($nid > 0) {
        drupal_set_message(t('修改成功！'), 'status', FALSE);
    }
}
}

function get_special_activities_allmessages($record){
    //农户
    $query = db_select('special_activities','SA');
    $query->join('farmer', 'F', 'F.special_activities_id=SA.special_activities_id');
    $query->fields('F');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $farmer_result = $query->execute()->fetchAll();

    //种植
    $query = db_select('special_activities','SA');
    $query->join('plant_info', 'PI', 'PI.special_activities_id=SA.special_activities_id');
    $query->join('farmer','F','F.farmer_id = PI.farmer_id');
    $query->join('plant','P','P.plant_id = PI.plant_id');
    $query->addField('F','farmer_name');
    $query->addField('F','addr_id');
    $query->addField('P','plant_name');
    $query->fields('PI');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $plant_result = $query->execute()->fetchAll();

    //土壤
    $query = db_select('special_activities','SA');
    $query->join('soil_info', 'SI', 'SI.special_activities_id=SA.special_activities_id');
    $query->join('farmer','F','F.farmer_id = SI.farmer_id');
    $query->addField('F','farmer_name');
    $query->addField('F','addr_id');
    $query->fields('SI');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $soil_result = $query->execute()->fetchAll();

    //礼物
    $query = db_select('special_activities','SA');
    $query->join('gift', 'G', 'G.special_activities_id=SA.special_activities_id');
    $query->join('farmer','F','F.farmer_id = G.farmer_id');
    $query->addField('F','farmer_name');
    $query->addField('F','addr_id');
    $query->fields('G');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $gift_result = $query->execute()->fetchAll();

    //施肥
    $query = db_select('special_activities','SA');
    $query->join('fertilizer_case', 'FC', 'FC.special_activities_id=SA.special_activities_id');
    $query->join('farmer','F','F.farmer_id = FC.farmer_id');
    $query->join('plant','P','P.plant_id = FC.plant_id');
    $query->addField('F','farmer_name');
    $query->addField('F','addr_id');
    $query->addField('P','plant_name');
    $query->fields('FC');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $fertilizer_result = $query->execute()->fetchAll();

    //回访
    $query = db_select('special_activities','SA');
    $query->join('revisit', 'R', 'R.special_activities_id=SA.special_activities_id');
    $query->join('farmer','F','F.farmer_id = R.farmer_id');
    $query->join('plant','P','P.plant_id = R.plant_id');
    $query->addField('F','farmer_name');
    $query->addField('F','addr_id');
    $query->addField('P','plant_name');
    $query->fields('R');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $revisit_result = $query->execute()->fetchAll();

    //测产
    $query = db_select('special_activities','SA');
    $query->join('plant_measure', 'PM', 'PM.special_activities_id=SA.special_activities_id');
    $query->join('farmer','F','F.farmer_id = PM.farmer_id');
    $query->join('plant','P','P.plant_id = PM.plant_id');
    $query->addField('F','farmer_name');
    $query->addField('F','addr_id');
    $query->addField('P','plant_name');
    $query->fields('PM');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $plant_measure_result = $query->execute()->fetchAll();

    //村落
    $query = db_select('special_activities','SA');
    $query->join('village', 'V', 'V.special_activities_id=SA.special_activities_id');
    $query->join('distributor','D','V.distributor_id = D.distributor_id');
    $query->addField('D','distributor_name');
    $query->fields('V');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $village_result = $query->execute()->fetchAll();

    //活动
    $query = db_select('special_activities','SA');
    $query->join('village_activity', 'VA', 'VA.special_activities_id=SA.special_activities_id');
    $query->join('distributor','D','VA.distributor_id = D.distributor_id');
    $query->addField('D','distributor_name');
    $query->fields('VA');
    $query->condition('SA.special_activities_id',$record->special_activities_id,'=');
    $village_activity_result = $query->execute()->fetchAll();

    $result =['farmer'=>$farmer_result,'plant'=>$plant_result,'soil'=>$soil_result,'gift'=>$gift_result,'fertilizer'=>$fertilizer_result,'revisit'=>$revisit_result,'plant_measure'=>$plant_measure_result,
        'village'=>$village_result,'village_activity'=>$village_activity_result];
    return $result;
}